package cn.xxd.xxdwebsso.controller;

import cn.xxd.common.CookieUtils;
import cn.xxd.common.UrlUtil;
import cn.xxd.common.UserUtil;
import cn.xxd.entity.LoginUser;
import cn.xxd.entity.ReturnT;
import cn.xxd.entity.ShopUser;
import cn.xxd.xxdssointerface.LoginService;
import cn.xxd.xxdssointerface.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LoginController {

    @Reference(version = "1.0.0", timeout = 100000)
    private LoginService loginService;

    @Reference(version = "1.0.0", timeout = 100000)
    private UserService userService;

    @Value("${AUTHORITY}")
    private String AUTHORITY;

    @Value("${HOMEURL}")
    private String HOMEURL;

    @Value("${SSOURL}")
    private String SSOURL;

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    @ResponseBody
    public ReturnT login(LoginUser loginUser, HttpServletRequest request, HttpServletResponse response) {
        ReturnT result = loginService.login(loginUser);
        //判断是否登录成功
        if (result.getCode() == 200) {
            String sessionId = result.getData().toString();
            //如果登录成功需要把token写入cookie
            CookieUtils.setCookie(request, response, AUTHORITY, sessionId);
        }
        //返回结果
        return result;
    }

    @RequestMapping(value = "/user/info")
    public String info(Model model, HttpServletRequest request) {
        // 获取当前用户Id
        String id = UserUtil.getCurrentUserId(request, AUTHORITY);
//        String username = loginUser.getUsername();
//        String name = loginUser.getName();
//        if("".equals(username)){
//            username = null;
//        }
//        if("".equals(name)){
//            name = null;
//        }
//        LoginUser user = loginService.getMsg(username,name);
        LoginUser user = loginService.getMsgById(id);
        String url = UrlUtil.getUrl(request);
        model.addAttribute("user", user);
        model.addAttribute("url", url);
        model.addAttribute("HOMEURL", HOMEURL);
        model.addAttribute("SSOURL", SSOURL);
        return "information";
    }

    @RequestMapping(value = "/user/edit", method = RequestMethod.POST)
    @ResponseBody
    public ReturnT edit(ShopUser user) {
        // 改bug 现在shopuser与loginuser中id一致 2020/02/21
        userService.editLoginUser(user.getId().toString(), user.getName());
        ReturnT result = loginService.edit(user);
        return result;
    }


}
